
class MyBlockingQueue{
    private String[] data=null;

    private int head=0;

    private int tail=0;

    private int size=0;

    public MyBlockingQueue(int capacity){
        data=new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (this){
            if(size>= data.length){
                //对列满了
                this.wait();
            }

            data[tail]=elem;
            tail++;
            if(tail>= data.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }

    public String take() {
        synchronized (this){
            //如果队列为空
           while(size==0){
               try {
                   this.wait();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
            String ret=data[head];
            head++;
            if(head>= data.length){
                head=0;
            }
            size--;
            this.notify();
            return ret;
            }
        }
}


public class Demo3 {
    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue(1000);
        Thread product=new Thread(()->{
            int n=0;
           while(true){
               try {
                   queue.put(n+"");
                   System.out.println("生产元素"+n);
                   n++;
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });

        Thread consume=new Thread(()->{
            int n=0;
            while(true){
                String s=queue.take();
                System.out.println("消费元素"+s);
                n++;
            }
        });
        product.start();
        consume.start();
    }
}
